use crate::model::{MJModel, TILEH, TILEW};
use log::info;
//use std::fs::File;
//use std::io::Write;
use tge::{
    context::Context,
    event::{event_check, event_register /*, timer_fire, timer_register*/},
    game::{Model, Render},
    render::sprite::{Sprites, Sprite},
    // render::style::{Color, Style},
    render::terminal::Term,
};

pub struct MJRender {
    pub term: Term,
    pub sprites: Sprites,
    pub boxes: Sprites,
}

impl MJRender {
    pub fn new() -> Self {
        //把34种不同麻将牌img存储在bs中
        //1~9WAN, 11~19TONG, 21~29TIAO,
        //31,32,33,34东西南北 / 35,36,37中发白
        //0, 10, 20, 30不用，填充为1.txt
        //直接bs[tile_num]即可访问到对应牌图形
        let mut bs = Sprites::new("boxes");
        for i in 0..38usize {
            let mut ts = Sprite::new(0, 0, TILEW as u16, TILEH as u16);
            let tfname = if i % 10 == 0 { 1 } else { i };
            let cn = format!("assets/mj/{}.txt", tfname);
            info!("load...{} {}", i, cn);
            ts.load_esc(&cn, 0, 0);
            bs.add(ts);
        }

        let t = Term::new();
        let mut s = Sprites::new("main");

        //14张牌
        for i in 0..14 {
            s.add_by_tag(
                Sprite::new(0, 0, TILEW as u16, TILEH as u16),
                &format!("t{}", i),
            );
        }

        event_register("MJ.RedrawTile", "draw_tile");

        Self {
            term: t,
            sprites: s,
            boxes: bs,
        }
    }

    pub fn draw_tile<G: Model>(&mut self, _context: &mut Context, model: &mut G) {
        let d = model.as_any().downcast_mut::<MJModel>().unwrap();
        let s = &mut d.pool[0..14];
        s.sort();
        for i in 0..14 {
            let l = self.sprites.get_by_tag(&format!("t{}", i));
            let bi = s[i] as usize;
            l.copy_content(&self.boxes[bi]);
            // if bi < 30 {
            //     l.content.set_str(
            //         1,
            //         1,
            //         format!("{}", bi % 10),
            //         Style::default().fg(Color::Indexed(237)),
            //     );
            // }
            l.set_pos((i % 7 * TILEW) as u16, (i / 7 * TILEH) as u16);
        }
    }
}

impl Render for MJRender {
    fn init(&mut self, context: &mut Context) {
        context.adapter.init(65, 14, 1.0, 1.0, "mahjong".to_string());
        self.term.init(context);
    }

    fn handle_event<G: Model>(&mut self, context: &mut Context, data: &mut G, _dt: f32) {
        if event_check("MJ.RedrawTile", "draw_tile") {
            self.draw_tile(context, data);
        }
    }

    fn handle_timer<G: Model>(&mut self, _context: &mut Context, _model: &mut G, _dt: f32) {}

    fn draw<G: Model>(&mut self, _context: &mut Context, _data: &mut G, _dt: f32) {
        self.term
            .draw(_context, |f| {
                for i in 0..14 {
                    let ss = self.sprites.get_by_tag(&format!("t{}", i));
                    f.render_widget(ss);
                }
            })
            .unwrap();
    }
}
